#
# @lc app=leetcode.cn id=538 lang=python
#
# [538] 把二叉搜索树转换为累加树
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def convertBST(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: Optional[TreeNode]
        """
        self.sum = 0
        self.loop(root)
        return root
    
    def loop(self, node):
        if not node:
            return 
        self.loop(node.right)
        self.sum += node.val
        node.val = self.sum
        self.loop(node.left)
        return

        
# @lc code=end

